package com.comments.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.ibatis.io.Resources;
import org.junit.Test;

import com.alibaba.fastjson.JSONObject;
import com.cvtech.pojo.EducationInfo;
import com.cvtech.pojo.ExperienceInfo;
import com.cvtech.pojo.ITSkills;
import com.cvtech.pojo.ProjectInfo;
import com.cvtech.pojo.ResumeInfo;
import com.hunter.pojo.Basic;
import com.hunter.pojo.Cv;
import com.hunter.pojo.Education;
import com.hunter.pojo.Expectation;
import com.hunter.pojo.Job;
import com.hunter.pojo.Project;
import com.hunter.pojo.Skill;

/**
 * @DESC 职品汇转换
 * @Author zhangzhenhua
 * @Date 2017年5月11日 下午4:29:27
 */
public class TransCV {

	public static void trans(ResumeInfo resume, CVObj ao) {

		// 主键表
		transCv(resume, ao);
		// 基本信息
		transBasic(resume, ao);
		// 教育经历
		transEdu(resume, ao);
		// 期望信息
		transExp(resume, ao);
		// 工作经历
		transJob(resume, ao);
		// 项目经历
		transPro(resume, ao);
		// 技能信息
		transSkill(resume, ao);

	}

	private static void transCv(ResumeInfo re, CVObj cv) {
		Cv c = new Cv();
		if (re.getFilePojo() != null)
			c.setFilepath(re.getFilePojo().getPath());
		c.setCv(re.getOriginal());
		c.setFlag(1);
		c.setCompanyId(1);
		cv.setCv(c);
	}

	private static Integer getMaxSallary(String sallary) {
		if (sallary != null) {
			Integer tmp = 0;
			Pattern p = Pattern.compile("[0-9]+");
			Matcher m = p.matcher(sallary);
			if (sallary.indexOf("年") != -1) {

				while (m.find()) {
					sallary = m.group();
					if (tmp < Integer.parseInt(sallary)) {
						tmp = Integer.parseInt(sallary);
					}
				}
				if (tmp != null && tmp != 0)
					return (tmp) / 12;

			} else {
				while (m.find()) {
					sallary = m.group();
					if (tmp < Integer.parseInt(sallary)) {
						tmp = Integer.parseInt(sallary);
					}
				}
				if (tmp != null && tmp != 0)
					return tmp;
			}

		}
		return null;
	}

	@Test
	public void test02() {
		System.out.println(new BigDecimal(""));

	}

	private static String getUid(String path) {
		if (path != null) {
			Pattern p = Pattern.compile("[0-9]{7,}");
			Matcher m = p.matcher(path);
			if (m.find()) {
				path = m.group();
			}
		}
		return null;
	}

	/**
	 * 日期格式转换 2016/06
	 * 
	 * @param time
	 * @return
	 */
	private static Date dateFormate(String time) {
		if (time != null) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Pattern p = Pattern.compile("([0-9]{4})[^0-9]+([0-9]{2})");
				Matcher m = p.matcher(time);
				if (m.find()) {
					if (m.groupCount() == 2) {
						String year = m.group(1);
						String month = m.group(2);
						return sdf.parse(year + "-" + month + "-00");
					}
				} else if (time.indexOf("至今") != -1) {
					return new Date();
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 日期格式转换 201606
	 * 
	 * @param time
	 * @return
	 */
	private static Date dateFormate2(String time) {
		if (time != null) {
			if (time.length() >= 6) {
				time = time.substring(0, 4) + "-" + time.substring(4, 6);
			} else {
				return null;
			}
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Pattern p = Pattern.compile("([0-9]{4})[^0-9]+([0-9]{2})");
				Matcher m = p.matcher(time);
				if (m.find()) {
					if (m.groupCount() == 2) {
						String year = m.group(1);
						String month = m.group(2);
						return sdf.parse(year + "-" + month + "-00");
					}
				} else if (time.indexOf("至今") != -1) {
					return new Date();
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Test
	public void test() {
		String str = "2015-03dada";
		System.out.println(dateFormate(str));
	}

	private static void transBasic(ResumeInfo re, CVObj ao) {
		Basic bn = new Basic();
		bn.setResumegrade(re.getResumeGrade());
		if (re.getMarried() != null && !re.getMarried().equals(""))
			bn.setMarriage(getMarrinum(re.getMarried()));
		bn.setFromwebsite(re.getFromWebSite());
		bn.setWebsiteresumeid(re.getWebSiteResumeID());
		bn.setKeyword(re.getKeyword());
		bn.setIdcard(re.getIDNO());
		bn.setEncouragement(re.getEncouragement());
		bn.setTeam(re.getTeam());
		bn.setWorkYear(dateFormate(re.getBeginworktime()));// 2000-09
		bn.setCertificate(re.getCertificate());
		bn.setComment(re.getPersonal());
		// bn.set English // 外语水平（ 并不特指英语）
		bn.setSchool(re.getSchool());// 排名 学校类型
		bn.setSchoolrankings(re.getSchoolRankings());
		bn.setSchooltype(re.getSchoolType());
		bn.setMajor(re.getSpeciality());
		bn.setAddress(re.getAddress());
		bn.setBirthPlace(re.getJiguan());// 籍贯
		bn.setCountry(re.getNationality());// 国籍
		bn.setNationality(re.getNational()); // 民族
		bn.setBirthday(re.getBirth());
		bn.setName(re.getName());
		bn.setHref(re.getHref());// 个人主页
		bn.setTitlestandard(re.getTitleStandard());
		bn.setAiminstitution(re.getAimInstitution());// 应聘机构（招聘网站发布的公司名称）
		bn.setAge(re.getAge());
		if (re.getSex() != null && !re.getSex().equals(""))
			bn.setGender(getGender(re.getSex()));
		bn.setHeight(re.getHigh()); // 身高（例如： 185cm）
		bn.setWeight(re.getWeight());//
		bn.setMobile(re.getMobile());
		bn.setPhone(re.getPhone());
		bn.setFax(re.getFax());
		bn.setEmail(re.getEmail());
		bn.setCity(re.getNowLocation()); // 设置城市
		bn.setEducation(re.getEducation());// 最高学历
		if (re.getAdvancedDegree() != null && !re.getAdvancedDegree().equals("")) {
			bn.setDegree(getDegreeNum(re.getAdvancedDegree())); // 学位
		} else if (re.getEducation() != null && !re.getEducation().equals("")) {
			bn.setDegree(getDegreeNum(re.getEducation())); // 学历
		}

		if (re.getExperience() != null && !re.getExperience().equals("")) {
			bn.setJobTime(Integer.parseInt(re.getExperience()));
		}
		bn.setTrade(re.getVocation());
		bn.setVocationstandard(re.getVocationStandard());
		bn.setPolitics(re.getPolitical());
		bn.setStartfrom(re.getStartFrom());// 到岗时间
		bn.setQq(re.getQQ());
		bn.setStudenttype(re.getStudentType());
		bn.setAppletter(re.getAppLetter());
		bn.setCompany(re.getLastCompany());
		bn.setTitle(re.getLastTitle());
		bn.setOverseaswork(re.getOverseasWork());
		bn.setJobhoppingfrequency(re.getJobHoppingFrequency());
		bn.setWorktype(re.getWorkType());
		bn.setMemo(re.getMemo());
		if (re.getGradeOfEnglish() != null && !re.getGradeOfEnglish().equals(""))
			bn.setGradeofenglish(JSONObject.toJSONString(re.getGradeOfEnglish()));
		if (re.getLanguagesSkills() != null && !re.getLanguagesSkills().equals(""))
			bn.setLanguagesskills(JSONObject.toJSONString(re.getLanguagesSkills()));
		if (re.getTrainingInfo() != null && !re.getTrainingInfo().equals(""))
			bn.setTraininginfo(JSONObject.toJSONString(re.getTrainingInfo()));
		bn.setFlag(0);
		bn.setJobStatus(getJobStatusNum(re.getSwitch()));
		// 行业id
		// 行业
		bn.setTradeId(getTradeId(re.getVocation()));
		// 期望薪资

		//
		bn.setCompanyId(1);
		bn.setJobtime(getJobTimeId(bn.getJobTime()));

		ao.setBasic(bn);
	}

	private static String getJobTimeId(Integer jobTime) {
		if (jobTime != null) {
			if (jobTime < 1) {
				return  "102";
			} else if (jobTime >= 1 && jobTime < 3) {
				return  "103";
			} else if (jobTime >= 3 && jobTime < 5) {
				return  "104";
			} else if (jobTime >= 5 && jobTime < 10) {
				return  "11";
			} else if (jobTime >= 10) {
				return  "12";
			}
		}
		return null;
	}

	private static Integer getTradeId(String trade) {
		// TODO Auto-generated method stub
		if (trade != null && !trade.equals("")) {
			String[] trades = { "IT", "互联网", "通信", "电子", "建设工程", "房地产", "物业管理", "金融", "消费品", "机械", "制造", "汽车", "车联网",
					"咨询", "公众服务", "外包", "文化", "传媒", "广告", "公关", "教育培训", "物流", "仓储", "运输", "贸易", "进出口", "医疗", "卫生", "健康",
					"能源", "化工", "环保", "政府", "公共事业", "农林牧渔", "其它", "计算机" };

			for (int i = 0; i < trades.length; i++) {
				if (trade.indexOf(trades[i]) != -1) {
					return (i + 1);
				}
			}
		}

		return null;
	}

	private static Integer getJobStatusNum(String s) {
		// TODO Auto-generated method stub
		if (s.indexOf("离职") != -1) {
			return 0;
		} else if (s.indexOf("在职") != -1) {
			return 1;
		}

		return null;
	}

	private static Integer getGender(String sex) {
		if (sex.indexOf("男") != -1) {
			return 1;
		} else if (sex.indexOf("女") != -1) {
			return 2;
		}
		return null;
	}

	/**
	 * @desc 0未知，1未婚，2已婚，3已育，4离异，5丧偶，6其他
	 * @param married
	 * @return
	 */
	private static int getMarrinum(String married) {
		if (married.indexOf("未婚") != -1) {
			return 1;
		} else if (married.indexOf("已婚") != -1) {
			return 2;
		} else if (married.indexOf("已育") != -1) {
			return 3;
		} else if (married.indexOf("离异") != -1) {
			return 4;
		} else if (married.indexOf("丧偶") != -1) {
			return 5;
		} else if (married.indexOf("其他") != -1) {
			return 6;
		}
		return 6;
	}
	// 博士、     研究生、MBA、        本科、大专、大学、       高中、中专、技校、 中技     、初中、小学    （双学位归并到本科，大学是指原文只提到大学，没有其他相关信息的情况）
	private static String getDegreeNum(String degree) {

		if (degree.contains("小学")||degree.contains("初中")) {
			return "1";
		} else if (degree.contains("高中")||degree.contains("高中")||degree.contains("中专")||degree.contains("技校")||degree.contains("中技")) {
			return "2";
		} else if (degree.contains("专科") || degree.contains("大专")) {
			return "3";
		} else if (degree.contains("本科") || degree.contains("学士")|| degree.contains("大学")|| degree.contains("双学位")) {
			return "4";
		} else if (degree.contains("硕士") || degree.contains("研究生")|| degree.contains("MBA")) {
			return "5";
		} else if (degree.contains("博士")) {
			return "6";
		} else if (degree.contains("博士后")) {
			return "7";
		}
		return null;
	}

	private static void transEdu(ResumeInfo resume, CVObj cv) {
		EducationInfo[] educationInfos = resume.getEducationInfo();
		if (educationInfos != null) {
			List<Education> educations = new ArrayList<Education>();
			for (EducationInfo education : educationInfos) {
				Education edu = new Education();
				edu.setStartTime(education.getStartDate());
				edu.setEndTime(education.getEndDate());
				edu.setSchool(education.getSchool());
				edu.setMajor(education.getSpeciality());
				if (education.getEducation() != null && !education.getEducation().equals(""))
					edu.setDegree(Integer.parseInt(getDegreeNum(education.getEducation())));
				edu.setDepartment(education.getDepartment());
				edu.setIsstudii(education.getIsStudii());
				edu.setInfo(education.getSummary());
				edu.setFlag(1);
				educations.add(edu);
			}
			cv.setEducations(educations);
		}

	}

	/**
	 * 期望信息
	 * 
	 * @param resume
	 * @param cv
	 */
	private static void transExp(ResumeInfo re, CVObj cv) {
		// Forwardlocation、ForwardVocation、AimSalary
		Integer sallary = getMaxSallary(re.getSalary());
		Expectation exp = new Expectation();
		exp.setFlag(1);
		exp.setExpectationIndustry(re.getForwardVocation());
		exp.setExpectationCity(re.getForwardlocation());
		exp.setExpectationSalary(getMaxSallary(re.getAimSalary()));
		exp.setPresentSalary(sallary);
		Integer tradeid = getTradeId(re.getForwardVocation());
		Integer cityid = getExpCityId(re.getForwardlocation());
		if (tradeid != null)
			exp.setExpectationIndustryId(tradeid + "");
		if (cityid != null)
			exp.setExpectationCityId(cityid + "");
		exp.setFlag(1);
		cv.setExpectation(exp);

		cv.getBasic().setExpectedSalary(getSallaryId(getMaxSallary(re.getAimSalary())));
		if (getSallaryId(sallary) != null) {
			cv.getBasic().setCurrentSalary(getSallaryId(sallary) + "");
		}

	}

	private static Integer getSallaryId(Integer expected_salary_ayear) {
		if (expected_salary_ayear != null) {

			int salaryId = 0;
			if (expected_salary_ayear <= 0) {
				salaryId = 148;
			} else if (expected_salary_ayear > 0 && expected_salary_ayear < 50000) {
				salaryId = 67;
			} else if (expected_salary_ayear >= 50000 && expected_salary_ayear < 100000) {
				salaryId = 68;
			} else if (expected_salary_ayear >= 100000 && expected_salary_ayear < 200000) {
				salaryId = 69;
			} else if (expected_salary_ayear >= 200000 && expected_salary_ayear < 300000) {
				salaryId = 70;
			} else if (expected_salary_ayear >= 300000 && expected_salary_ayear < 500000) {
				salaryId = 71;
			} else if (expected_salary_ayear >= 500000 && expected_salary_ayear < 1000000) {
				salaryId = 72;
			} else if (expected_salary_ayear >= 1000000) {
				salaryId = 73;
			}
			return salaryId;

		}
		return null;
	}

	private int getSalaryId(int expected_salary_ayear) {
		int salaryId = 0;
		if (expected_salary_ayear <= 0) {
			salaryId = 148;
		} else if (expected_salary_ayear > 0 && expected_salary_ayear < 50000) {
			salaryId = 67;
		} else if (expected_salary_ayear >= 50000 && expected_salary_ayear < 100000) {
			salaryId = 68;
		} else if (expected_salary_ayear >= 100000 && expected_salary_ayear < 200000) {
			salaryId = 69;
		} else if (expected_salary_ayear >= 200000 && expected_salary_ayear < 300000) {
			salaryId = 70;
		} else if (expected_salary_ayear >= 300000 && expected_salary_ayear < 500000) {
			salaryId = 71;
		} else if (expected_salary_ayear >= 500000 && expected_salary_ayear < 1000000) {
			salaryId = 72;
		} else if (expected_salary_ayear >= 1000000) {
			salaryId = 73;
		}
		return salaryId;
	}

	private static Integer getExpCityId(String city) {
		if (city != null && !city.equals("")) {
			try {
				// 从city_simple中获取城市
				InputStream in = Resources.getResourceAsStream("city_simple.txt");
				List<String> citys = new ArrayList<String>();
				BufferedReader br2 = new BufferedReader(new InputStreamReader(in, "utf-8"));
				String tmp2 = null;
				while ((tmp2 = br2.readLine()) != null) {
					citys.add(tmp2);
				}
				return getPcd(city, citys);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	private static Integer getPcd(String pcd, List<String> pcdlist) {
		// TODO Auto-generated method stub
		for (int i = 0; i < pcdlist.size(); i++) {
			if (pcd.indexOf(pcdlist.get(i)) != -1) {
				if (pcdlist.get(i).length() > 1)
					return i;
			}
		}
		return null;
	}

	private static void transJob(ResumeInfo resume, CVObj cv) {
		ExperienceInfo[] experienceInfos = resume.getExperienceInfo();
		if (experienceInfos != null) {
			List<Job> jobs = new ArrayList<Job>();
			for (ExperienceInfo exper : experienceInfos) {
				Job job = new Job();
				job.setStartTime(exper.getStartDate());
				job.setEndTime(exper.getEndDate());
				job.setCompany(exper.getCompany());
				job.setCity(exper.getLocation());
				job.setTrade(exper.getVocation());
				if (exper.getSize() != null && !exper.getSize().equals(""))
					job.setCompanysize(exper.getSize().replace("人", ""));
				job.setCompanynature(exper.getType());
				job.setDepartment(exper.getDepartment());
				job.setTitle(exper.getTitle());
				if (getMaxSallary(exper.getSalary()) != null)
					job.setSalary(getMaxSallary(exper.getSalary()) + "");
				job.setReport(exper.getLeader());
				if (exper.getUnderlingNumber() != null && !exper.getUnderlingNumber().equals(""))
					job.setMember(exper.getUnderlingNumber());// 下属人数
				job.setReason(exper.getReasonOfLeaving());
				job.setInfo(exper.getSummary());// 详细介绍
				job.setFlag(0);
				jobs.add(job);
			}
			cv.setJobs(jobs);
		}

	}

	private static void transPro(ResumeInfo resume, CVObj cv) {
		ProjectInfo[] projectInfos = resume.getProjectInfo();
		if (projectInfos != null) {
			List<Project> pros = new ArrayList<Project>();
			for (ProjectInfo project : projectInfos) {
				Project pro = new Project();
				pro.setStartTime(project.getStartDate());
				pro.setEndTime(project.getEndDate());
				pro.setProjectName(project.getProjectName());
				pro.setTitle(project.getTitle());// 项目职务
				pro.setContent(project.getProjectDescription());
				pro.setDuty(project.getResponsibilities());
				pro.setFlag(0);
				pros.add(pro);
			}
			cv.setProjects(pros);
		}

	}

	/**
	 * <p>
	 * 获取技能信息
	 * </p>
	 * 
	 * @param resume
	 * @param cv
	 */
	private static void transSkill(ResumeInfo resume, CVObj cv) {
		ITSkills[] skills = resume.getITSkills();
		if (skills != null) {
			List<Skill> sks = new ArrayList<Skill>();
			for (ITSkills skill : skills) {
				Skill sk = new Skill();
				sk.setSkillName(skill.getSkillType());
				sk.setInfo(skill.getCompetencyLevel());
				if (skill.getTimeOfUse() != null && !skill.getTimeOfUse().equals("")) {
					Pattern p = Pattern.compile("[0-9]+");
					Matcher m = p.matcher(skill.getTimeOfUse());
					if (m.find()) {
						sk.setSkillExperience(Integer.parseInt(m.group()));
					}
				}
				sk.setFlag(1);
				sks.add(sk);

			}
			cv.setSkills(sks);
		}

	}

}
